package com.kehongborui.portal.service.impl;

import com.kehongborui.data.domain.Staff;
import com.kehongborui.data.repository.StaffRepository;
import com.kehongborui.portal.exception.SczcException;
import com.kehongborui.portal.model.StaffModel;
import com.kehongborui.portal.service.StaffService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import static com.kehongborui.portal.enums.Error.STAFF_IS_EXISTS;

/**
 * @author zhang peng yang ming
 * @CopyRight (C) http://www.csdn.com
 * @brief
 * @email 122162005@qq.com
 * @date 2018-09-26
 */
@Service
public class StaffServiceImpl implements StaffService {
    @Autowired
    private StaffRepository staffRepository;


    @Override
    public StaffModel save(StaffModel model) {
        Staff staff = new Staff();
        BeanUtils.copyProperties(model, staff);
        // 根据身份证号码，姓名 校验重复
//        ExampleMatcher matcher = ExampleMatcher.matchingAny().withIgnorePaths("name", "dkdkdk")
//                .withMatcher("name", ExampleMatcher.GenericPropertyMatchers.exact())
//                .withMatcher("staffNo", ExampleMatcher.GenericPropertyMatchers.exact())
//                .withMatcher("idCardNo", m -> m.exact());

        if (staffRepository.exists(Example.of(staff, matchingAny(Staff.class, "staffNo", "idCardNo")))) {
            throw new SczcException(STAFF_IS_EXISTS.getDesc());
        }

        Staff save = staffRepository.save(staff);
        BeanUtils.copyProperties(save, model);
        return model;
    }

    @Override
    public List<StaffModel> findByDeptId(Integer id) {
        List<Staff> staffList = staffRepository.findAllByDeptId(id);

        return staffList.stream().map(s -> {
            StaffModel model = new StaffModel();
            BeanUtils.copyProperties(s, model);
            return model;
        }).collect(Collectors.toList());
    }

    /**
     * 获取 ExampleMatcher 对象，该对象只匹配 propertiesPath 指定的字段
     *
     * @param t              匹配器要匹配的目标对象的类型
     * @param propertiesPath 匹配指定的字段(需要作为条件的字段)
     * @param <T>
     * @return
     */
    public <T> ExampleMatcher matchingAny(Class<T> t, String... propertiesPath) {
        // 获取t类型所有的字段
        Field[] fields = t.getDeclaredFields();
        List<String> properties = Arrays.asList(propertiesPath);

        List<String> ignorePaths = new ArrayList<>();

        for (Field field : fields) {
            if (!properties.contains(field.getName())) {
                // 忽略未被指定的字段
                ignorePaths.add(field.getName());
            }
        }
        // 创建临时数组
        String[] ignorePathsArray = new String[ignorePaths.size()];
        int index = 0;
        for (String path : ignorePaths) {
            ignorePathsArray[index++] = path;
        }

        return ExampleMatcher.matchingAny().withIgnorePaths(ignorePathsArray);
    }

    @Override
    public Page<Staff> findAll(StaffModel model, int currentPage, int pageSize) {
        ExampleMatcher matcher = ExampleMatcher.matching();
        Staff staff = new Staff();
        BeanUtils.copyProperties(model, staff);
        Example<Staff> example = Example.of(staff, matcher);
        PageRequest request = new PageRequest(currentPage - 1, pageSize, new Sort(new Sort.Order(Sort.Direction.ASC, "name")));
        Page<Staff> staffPage = staffRepository.findAll(example, request);
        // 获取总页数
        int totalPage = staffPage.getTotalPages();

        return staffPage;
//        return staffPage.getContent().stream().map(e -> {
//            StaffModel staffModel = new StaffModel();
//            BeanUtils.copyProperties(e, staffModel);
//            return staffModel;
//        }).collect(Collectors.toList());
    }
}
